<template>
  <view class="container">
    <!-- 空购物车提示 -->
    <view class="empty-cart" v-if="cartList.length === 0">
      <image src="/static/empty-cart.png" mode="aspectFit"></image>
      <text>购物车还是空的</text>
      <button class="go-shopping" @tap="goShopping">去逛逛</button>
    </view>
    
    <!-- 购物车列表 -->
    <view class="cart-list" v-else>
      <view class="cart-item" v-for="(item, index) in cartList" :key="index">
        <checkbox :checked="item.selected" @tap="toggleSelect(index)"></checkbox>
        <image :src="item.image" mode="aspectFill" @tap="goDetail(item)"></image>
        <view class="item-info">
          <text class="title">{{item.title}}</text>
          <text class="price">¥{{item.price}}</text>
        </view>
        <view class="quantity-control">
          <text class="minus" @tap="decreaseQuantity(index)">-</text>
          <input type="number" v-model="item.quantity" @blur="updateQuantity(index)" />
          <text class="plus" @tap="increaseQuantity(index)">+</text>
        </view>
        <text class="delete" @tap="deleteItem(index)">×</text>
      </view>
    </view>
    
    <!-- 底部结算栏 -->
    <view class="settlement-bar" v-if="cartList.length > 0">
      <view class="select-all">
        <checkbox :checked="isAllSelected" @tap="toggleSelectAll"></checkbox>
        <text>全选</text>
      </view>
      <view class="total-info">
        <text>合计：</text>
        <text class="price">¥{{totalPrice}}</text>
      </view>
      <button class="checkout-btn" @tap="checkout">结算({{selectedCount}})</button>
    </view>
  </view>
</template>

<script>
import { cartApi } from '@/api/index'
import { showToast, showModal } from '@/utils/common'

export default {
  data() {
    return {
      cartList: []
    }
  },
  computed: {
    isAllSelected() {
      return this.cartList.length > 0 && this.cartList.every(item => item.selected)
    },
    selectedCount() {
      return this.cartList.filter(item => item.selected).length
    },
    totalPrice() {
      return this.cartList
        .filter(item => item.selected)
        .reduce((total, item) => {
          return total + parseFloat(item.price) * item.quantity
        }, 0)
        .toFixed(2)
    }
  },
  onShow() {
    this.getCartList()
  },
  methods: {
    // 获取购物车列表
    async getCartList() {
      try {
        const res = await cartApi.getCartList()
        this.cartList = res.map(item => ({
          ...item,
          selected: true
        }))
      } catch (error) {
        showToast('购物车列表加载失败')
      }
    },
    
    // 切换商品选择状态
    async toggleSelect(index) {
      const item = this.cartList[index]
      try {
        await cartApi.selectCartItem(item.id, !item.selected)
        item.selected = !item.selected
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 切换全选状态
    async toggleSelectAll() {
      const newStatus = !this.isAllSelected
      try {
        await cartApi.selectAllCartItems(newStatus)
        this.cartList.forEach(item => {
          item.selected = newStatus
        })
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 增加商品数量
    async increaseQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity >= item.stock) {
        showToast('库存不足')
        return
      }
      
      try {
        await cartApi.updateCartQuantity(item.id, {
          quantity: item.quantity + 1
        })
        item.quantity++
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 减少商品数量
    async decreaseQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity <= 1) {
        showToast('商品数量不能小于1')
        return
      }
      
      try {
        await cartApi.updateCartQuantity(item.id, {
          quantity: item.quantity - 1
        })
        item.quantity--
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 更新商品数量
    async updateQuantity(index) {
      const item = this.cartList[index]
      if (item.quantity < 1) {
        item.quantity = 1
      } else if (item.quantity > item.stock) {
        item.quantity = item.stock
      }
      
      try {
        await cartApi.updateCartQuantity(item.id, {
          quantity: item.quantity
        })
      } catch (error) {
        showToast('操作失败')
      }
    },
    
    // 删除商品
    async deleteItem(index) {
      const item = this.cartList[index]
      try {
        await showModal('提示', '确定要删除这个商品吗？')
        await cartApi.deleteCartItem(item.id)
        this.cartList.splice(index, 1)
        showToast('删除成功')
      } catch (error) {
        if (error) {
          showToast('删除失败')
        }
      }
    },
    
    // 去购物
    goShopping() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    
    // 去商品详情
    goDetail(item) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${item.productId}`
      })
    },
    
    // 结算
    checkout() {
      if (this.selectedCount === 0) {
        showToast('请选择商品')
        return
      }
      
      const selectedItems = this.cartList
        .filter(item => item.selected)
        .map(item => ({
          id: item.id,
          quantity: item.quantity
        }))
      
      uni.navigateTo({
        url: `/pages/order/confirm?items=${JSON.stringify(selectedItems)}`
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100rpx;
}

.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 200rpx;
  
  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 30rpx;
  }
  
  .go-shopping {
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    background: #ff0000;
    color: #fff;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

.cart-list {
  padding: 20rpx;
  
  .cart-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 8rpx;
    
    checkbox {
      margin-right: 20rpx;
    }
    
    image {
      width: 160rpx;
      height: 160rpx;
      margin-right: 20rpx;
      border-radius: 8rpx;
    }
    
    .item-info {
      flex: 1;
      
      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      
      .price {
        font-size: 32rpx;
        color: #ff0000;
      }
    }
    
    .quantity-control {
      display: flex;
      align-items: center;
      margin: 0 20rpx;
      
      .minus, .plus {
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        background: #f5f5f5;
        border-radius: 30rpx;
      }
      
      input {
        width: 80rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        margin: 0 20rpx;
        background: #f5f5f5;
        border-radius: 8rpx;
      }
    }
    
    .delete {
      font-size: 40rpx;
      color: #999;
      padding: 20rpx;
    }
  }
}

.settlement-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  
  .select-all {
    display: flex;
    align-items: center;
    
    checkbox {
      margin-right: 10rpx;
    }
    
    text {
      font-size: 28rpx;
      color: #333;
    }
  }
  
  .total-info {
    flex: 1;
    text-align: right;
    
    text {
      font-size: 28rpx;
      color: #333;
      
      &.price {
        font-size: 36rpx;
        color: #ff0000;
        font-weight: bold;
      }
    }
  }
  
  .checkout-btn {
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: #ff0000;
    color: #fff;
    border-radius: 40rpx;
    margin-left: 20rpx;
    font-size: 28rpx;
  }
}
</style> 